import Controller from "./controller";
import { password_verify, password_hash } from '../utils/crypto';

export default class UserController extends Controller {
    config: {
        Fields: {
            Account: string,
            PWD: string,
            Status: string
        },
        Table: string,
        Error: {
            AccountOrPWDError: string,
            CannotForget: string
        }
    }
    /**
     * 登陆
     * @param post 
     */
    async login(post) {
        let Account = this.I(this.config.Fields.Account);
        let PWD = this.I(this.config.Fields.PWD);
        if (Account && PWD) {

        } else {
            throw this.config.Error.AccountOrPWDError
        }
        let u = await this.M(this.config.Table).where({ [this.config.Fields.Account]: Account, [this.config.Fields.Status]: 1 }).fields(`UID,${this.config.Fields.PWD}`).find()
        if (u) {
            if (password_verify(PWD, u[this.config.Fields.PWD])) {
                this._session('UID', u.UID)
                let user = await this.R(this.config.Table).where({ UID: u.UID }).find()
                return user;
            } else {
                throw this.config.Error.AccountOrPWDError
            }
        } else {
            throw this.config.Error.AccountOrPWDError
        }
    }
    /**
     * 刷新后的再次登陆
     * @param post 
     */
    async relogin(post) {
        let UID = this._session('UID');
        if (UID > 0) {
            return await this.R(this.config.Table).where({ UID }).find()
        } else {
            throw this.config.Error.AccountOrPWDError
        }
    }
    /**
     * 注册时返回除Account和密码的其它需要处理的字段，
     * @param post 
     */
    protected async registData(post) {
        return {}
    }
    /**
     * 注册成功回调，需要在此处调用this.commit()
     * @param rs 
     */
    protected async registHandler(rs) {
        this.commit()
        return true;
    }
    /**
     * 注册
     * @param post 
     */
    async regist(post) {
        let Account = this.I(this.config.Fields.Account);
        let PWD = this.I(this.config.Fields.PWD);
        if (
            (Account instanceof String && Account.length > 3)
            && (PWD instanceof String && PWD.length > 6)
        ) {
            this.startTrans()
            let rs = this.M(this.config.Table).add(Object.assign(await this.registData(post), { Account, PWD: password_hash(PWD) }))
            return await this.registHandler(rs)
        } else {
            throw this.config.Error.AccountOrPWDError
        }
    }
    /**
     * 找回密码逻辑
     */
    async forget() {
        throw this.config.Error.CannotForget
        // 重置密码时需要使用
        // password_hash(pwd)
    }
    /**
     * 退出登录逻辑
     */
    async logout() {
        this._session(null)
        return true;
    }
}